/*
 * PersistenceEngine.java
 *
 * Created on June 9, 2007, 2:30 PM
 *
 * To change this template, choose Tools | Template Manager
 * and open the template in the editor.
 */

package com.registration.utils;

import org.hibernate.proxy.HibernateProxy;
import org.springframework.orm.hibernate3.HibernateTemplate;

/**
 *
 * @author Lruiz
 */
public class PersistenceEngine {
    private HibernateTemplate hibernateTemplate;
    /** Creates a new instance of PersistenceEngine */
    public PersistenceEngine() {
    }
    
    public void setHibernateTemplate(HibernateTemplate hibernateTemplate){
        this.hibernateTemplate = hibernateTemplate;
    }
    public void attach(Object object){
        if(object != null){
            hibernateTemplate.refresh(object);
        }
    }
    public void detach(Object object){
        if(object != null){
            hibernateTemplate.evict(object);
        }        
    }
    
    public void refresh(Object object){
        if(object != null){
            hibernateTemplate.refresh(object);
        }
    }
    
    public void flush(){
        hibernateTemplate.flush();
    }
    
    public boolean isInstanceOf(Object obj, Class clazz){
        Class realclass = getClass(obj);
        return clazz.isAssignableFrom(realclass);
    }
    
    public Class getClass(Object obj){
        return obj instanceof HibernateProxy ? 
            ((HibernateProxy)obj).getHibernateLazyInitializer()
            .getPersistentClass() : obj.getClass();
    }
}
